package spzx.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import org.checkerframework.checker.units.qual.A;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import spzx.mapper.CategoryMapper;

import java.util.ArrayList;
import java.util.List;

@Component
public class CategoryReadListener implements ReadListener<CategoryExcelVo> {
    private static final int BATCH_COUNT = 5;

    private List<CategoryExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    //@Autowired
    CategoryMapper categoryMapper;
    /*StringRedisTemplate stringRedisTemplate;

    public CategoryReadListener(CategoryMapper categoryMapper, StringRedisTemplate stringRedisTemplate){
        this.categoryMapper = categoryMapper;
        this.stringRedisTemplate = stringRedisTemplate;
    }*/

    public CategoryReadListener(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }

    @Override
    public void invoke(CategoryExcelVo categoryExcelVo, AnalysisContext analysisContext) {
        cachedDataList.add(categoryExcelVo);
        if(cachedDataList.size() == 5){
            categoryMapper.addCategoryList(cachedDataList);
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);//重新创建集合
        }
        //categoryMapper.addCategory(categoryExcelVo);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(cachedDataList.size() > 0){
            categoryMapper.addCategoryList(cachedDataList);
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
        /*//所有行读取完毕后，清空缓存
        stringRedisTemplate.delete("categoryCache");*/
    }
}
